package com.sogoodsoft.service.crm;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sogoodsoft.dao.common.CommonHibernateDao;
import com.sogoodsoft.dao.crm.DocFileDao;
import com.sogoodsoft.dao.crm.DocumentDao;
import com.sogoodsoft.entity.crm.DocFile;
import com.sogoodsoft.entity.crm.Document;
import com.sogoodsoft.service.common.AbstractService;
import com.sogoodsoft.util.CommonUtils;

@Component
@Transactional
public class DocumentService extends AbstractService < Document, Long > {

    @Autowired
    private DocumentDao documentDao;

    @Autowired
    private DocFileDao docFileDao;

    @Override
    public CommonHibernateDao < Document, Long > getDao() {
        return documentDao;
    }

    /**
     * 保存附件及实体
     * @param upload
     * @param fileFileName
     * @param fileContentType
     * @param doc
     * @throws IOException
     */
    public void saveFile(List < File > upload, List < String > fileFileName, List < String > fileContentType, Document doc)
        throws IOException {
        Date d = new Date();

        if (upload != null && upload.size() > 0) {
            //先删除该docid相关的附件表记录
            docFileDao.deleteByDocId(doc.getId());
            
            String[] fxt = {};// 文件后缀
            String urlPath = "/attachfiles/docfile";    //路径文件夹
            
            String desFilePath = ServletActionContext.getServletContext().getRealPath(urlPath);
            String desFilePathTmp = desFilePath;// 保存临时路径
            File filePath = new File(desFilePath);
            // 创建目录
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            for (int i = 0; i < upload.size(); i++) {
                String fileName = "\\";   //文件名
                desFilePath = desFilePathTmp;
                DateFormat dft = new SimpleDateFormat("yyyyMMddHHmmss");
                fileName +=  dft.format(d) + i;
                desFilePath += fileName;
                fxt = fileFileName.get(i).split("\\.");
                desFilePath += "." + fxt[1];
                CommonUtils.uploadFile(upload.get(i), desFilePath);

                // 保存到附件表
                DocFile docFile = new DocFile();
                docFile.setDocid(doc.getId());
                docFile.setName(fileFileName.get(i));   //原文件名
//                docFile.setExt(fileContentType.get(i)); //文件MIME
                docFile.setExt(fxt[1]); //后缀名
                docFile.setStorename(urlPath+fileName+"."+fxt[1]); //新文件名，不带后缀名
                docFileDao.save(docFile);
            }
        }
    }
}
